package com.yeebo.exception;

import com.yeebo.enums.ResultCode;
import com.yeebo.utils.ResponseUtils;
import com.yeebo.vo.Result;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 基于ControllerAdvice+ExceptionHandler实现全局Controller层的异常处理与统一抛出
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    Result handle(Exception ex) {
        if (ex instanceof ServiceException) {
            ServiceException serviceException = (ServiceException) ex;
            return ResponseUtils.error(serviceException.getCode(), serviceException.getMessage());
        } else if (ex instanceof ShiroException || ex instanceof UnauthenticatedException) {
            return ResponseUtils.error(ResultCode.PERMISSION_DENY.getCode(), ResultCode.PERMISSION_DENY.getMessage());
        } else {
            logger.error("[系统异常]：{}", ex);
            return ResponseUtils.error(ex.getMessage());
        }
    }

}
